<template>
	<view class="container">
		<!-- 顶部核心图标 -->
		<image class="core-icon" src="/static/group_1.png" mode="aspectFit" />
		<!-- 标题 -->
		<view class="title">团购自助核销</view>
		<!-- 第一个下拉选择框 -->
		<picker class="picker-row" :range="platforms" @change="onPlatformChange">
			<view class="input-row">
				<!-- 平台选择显示 -->
				<text :class="['input-placeholder', selectedPlatform ? 'selected' : '']">
					{{ selectedPlatform || '点击选择兑换平台' }}
				</text>
				<image class="input-icon" src="/static/group_2.png" />
			</view>
		</picker>
		<!-- 第二个输入框（带扫码） -->
		<view class="input-row">
			<input class="input-field" v-model="code" placeholder="输入卡券兑换码或者扫码" />
			<image class="input-icon scan" src="/static/group.png" @tap="scanCode" />
		</view>
		<!-- 第三个下拉选择框 -->
		<picker class="picker-row" :range="stores" @change="onStoreChange">
			<view class="input-row">
				<!-- 门店选择显示 -->
				<text :class="['input-placeholder', selectedStore ? 'selected' : '']">
					{{ selectedStore || '点击选择兑换门店' }}
				</text>
				<image class="input-icon" src="/static/group_2.png" />
			</view>
		</picker>
		<!-- 提交按钮 -->
		<button class="submit-btn" @tap="submit">提交</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code: '',
				selectedPlatform: '',
				selectedStore: '',
				platforms: ['美团&大众点评', '抖音'],
				stores: [], // 门店名称列表
				storeList: [], // 门店完整信息（可用于后续操作，比如获取门店id等）
				lat: '', // 经纬度
				lng: ''
			}
		},
		onLoad() {
			this.$xyfun.loc().then((res) => {
				this.lat = res.latitude;
				this.lng = res.longitude;
				this.loadStoreData();
			}, () => {
				this.loadStoreData();
			})
		},
		methods: {
			scanCode() {
				uni.scanCode({
					success: (res) => {
						console.log(res);
						console.log(JSON.stringify(res, null, 2)); // 美化输出

						let raw = res.result;
						let code = raw; // 默认直接用原始扫码结果

						// 判断是否是抖音短链接
						// 格式一般是 https://v.douyin.com/xxxxx/ 后面还有个斜杠
						const douyinRegex = /^https?:\/\/v\.douyin\.com\/([a-zA-Z0-9]+)\/?$/;

						const match = raw.match(douyinRegex);
						if (match) {
							// 提取出中间的码
							code = match[1];
						}

						this.code = code;
						console.log('最终显示的码：', this.code);
					},
					fail: () => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},
			onPlatformChange(e) {
				this.selectedPlatform = this.platforms[e.detail.value];
			},
			onStoreChange(e) {
				this.selectedStore = this.stores[e.detail.value];
			},
			submit() {
				if (!this.selectedPlatform || !this.code || !this.selectedStore) {
					uni.showToast({
						title: '请选择完整信息',
						icon: 'none'
					});
					return;
				}
				const user = uni.getStorageSync('xyvenue:user');
				if (!user || !user.id) {
					uni.showToast({
						title: '用户未登录',
						icon: 'none'
					});
					return;
				}
				const userId = user.id;
				// 获取平台标识
				let platformCode = '';
				if (this.selectedPlatform === '美团&大众点评') {
					platformCode = 'MT';
				} else if (this.selectedPlatform === '抖音') {
					platformCode = 'DY';
				}
				// 获取 store_id
				const selectedStoreObj = this.storeList.find(item => item.name === this.selectedStore);
				if (!selectedStoreObj) {
					uni.showToast({
						title: '找不到所选门店',
						icon: 'none'
					});
					return;
				}
				const storeId = selectedStoreObj.id;

				// 获取券数据类型
				let couponDataType = '1'; // 默认 1
				if (platformCode === 'DY' && this.code.startsWith('http')) {
					couponDataType = '2'; // 抖音扫码才是 2
				}
				// TODO: 提交逻辑
				// 发起请求
				this.$api.post({
					url: '/Shande/prepareCouponVerification',
					loadingTip: '提交中...',
					data: {
						coupon_data: this.code, //核销券码
						platform: platformCode, //平台：美团 ：MT  抖音 ：DY
						store_id: storeId, //核销使用门店id
						user_id: userId, //用户id
						coupon_data_type: couponDataType //券数据类型编码  1 手工输入  2 二维码扫码
					},
					success: (res) => {
						if (res && res.status === 'used_or_invalid') {
							uni.showToast({
								title: res.msg || '该券已被核销，请检查后重试',
								icon: 'none'
							});
							console.warn('券不可用：', res);
						} else {
							uni.showToast({
								title: '核销成功，已存入优惠券,预约即可使用',
								icon: 'none',
								duration: 1400
							});

							console.log('核销准备成功：', res);

							// 2秒后跳转到首页
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/user/coupon/list'
								});
							}, 1500);
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '核销失败，请检查后重试',
							icon: 'none'
						});
						console.error('核销准备失败：', err);
					}
				});
			},
			loadStoreData() {
				this.$api.get({
					url: '/store/lists',
					loadingTip: '加载中...',
					data: {
						lat: this.lat,
						lng: this.lng,
						search: '',
						category_id: 0,
						page: 1,
					},
					success: res => {
						const list = res.data || [];
						console.log("list:" + list);
						this.storeList = list;
						this.stores = list.map(item => item.name); // 提取门店名数组用于 picker 渲染
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #f8f8f8;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 0 80rpx;
	}

	.core-icon {
		width: 380rpx;
		height: 380rpx;
		margin-top: 80rpx;
		display: block;
	}

	.title {
		font-size: 45rpx;
		font-weight: bold;
		color: #222;
		text-align: center;
		margin-bottom: 50rpx;
		margin-top: -80rpx;
	}

	.picker-row {
		width: 100%;
		display: block;
	}

	.input-row {
		width: 100%;
		background: #fff;
		border-radius: 20rpx;
		margin-bottom: 36rpx;
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		height: 100rpx;
		box-sizing: border-box;
		font-size: 36rpx;
		position: relative;
	}

	.input-placeholder {
		color: #bbb;
		flex: 1;
		font-size: 36rpx;

	}

	.input-field {
		flex: 1;
		border: none;
		outline: none;
		font-size: 36rpx;
		background: transparent;
		color: #222;
	}

	.input-icon {
		width: 48rpx;
		height: 28rpx;
		margin-left: 16rpx;
	}

	.input-icon.scan {
		width: 54rpx;
		height: 54rpx;
	}

	.submit-btn {
		width: 100%;
		height: 100rpx;
		background: #ff6133;
		color: #fff;
		font-size: 36rpx;
		border-radius: 20rpx;
		margin-top: 80rpx;
		font-weight: bold;
		letter-spacing: 2rpx;
	}

	.input-placeholder.selected {
		color: #222; // 黑色
	}
</style>